<template> 
    <!--新增/编辑界面 MoOrder mo_order-->
        <el-form :model="editForm"  label-width="120px" :rules="editFormRules" ref="editFormRef"> 
				<el-descriptions :column="3"   border> 
					<el-descriptions-item label="订单编号">{{editForm.id}}</el-descriptions-item>
					<el-descriptions-item label="下单机构" :span="2">{{editForm.obranchName}}</el-descriptions-item>
					<el-descriptions-item label="折前总价">￥{{editForm.moFinalFee}}元</el-descriptions-item>
					<el-descriptions-item label="折扣率">{{editForm.odisRate}}%</el-descriptions-item>
					<el-descriptions-item label="折后总价">￥{{editForm.ofinalFee}}元</el-descriptions-item>
					<el-descriptions-item label="状态"><mdp-select showStyle="tag" item-code="mo_order_status" v-model="editForm.status" :disabled="true"/></el-descriptions-item> 
					<el-descriptions-item label="操作类型"><mdp-select showStyle="tag" item-code="mo_ooper" v-model="editForm.ooper" :disabled="true"/></el-descriptions-item> 
 				</el-descriptions>
				<el-tabs modelValue="1"> 
					<el-tab-pane label="订单信息" name="1" >  
						<el-row>
							<el-col :span="8"> 
								
								<el-form-item label="订单状态" prop="status">  
									<mdp-select item-code="mo_order_status" :disabled="true" v-model="editForm.status" @change="editSomeFields(editForm,'status',$event)"/>
								</el-form-item>   
								
							</el-col>
							<el-col :span="8">
								<el-form-item label="订单来源" prop="osource">  
									<mdp-select item-code="osource" v-model="editForm.osource" @change="editSomeFields(editForm,'osource',$event)"/> 
								</el-form-item>    
							</el-col>
							<el-col :span="8"> 
								<el-form-item label="创建时间" prop="ctime">
									<el-date-picker type="date" placeholder="选择日期" :disabled="true" v-model="editForm.ctime"  value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD"/>
								</el-form-item>      
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="8"> 
								<el-form-item label="购买人数" prop="ousers">
									<el-input-number v-model="editForm.ousers" :min="0" :max="20000" :disabled="true"  @change="editSomeFields(editForm,'ousers',$event)"/>
								</el-form-item>  
							</el-col>
							<el-col :span="8"> 
								<el-form-item label="购买天数" prop="odays">
									<el-input-number v-model="editForm.odays" :min="0" :max="20000" :disabled="true" @change="editSomeFields(editForm,'odays',$event)"/>天
								</el-form-item> 
							</el-col>
							<el-col :span="8">  
								<el-form-item label="购买模块数" prop="omodules">
									<el-input-number v-model="editForm.omodules" :min="0" :max="200000" :disabled="true"  @change="editSomeFields(editForm,'omodules',$event)"/>
								</el-form-item>  
							</el-col> 
						</el-row>
						<el-row> 
							<el-col :span="8">
								<el-form-item label="开始日期" prop="startTime">
									<el-date-picker type="date" placeholder="选择日期" :disabled="true" v-model="editForm.startTime"  value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD"  @change="editSomeFields(editForm,'startTime',$event)"/>
								</el-form-item>  
							</el-col>
							<el-col :span="8">
								<el-form-item label="截止日期" prop="endTime">
									<el-date-picker type="date" placeholder="选择日期" :disabled="true" v-model="editForm.endTime"  value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD"  @change="editSomeFields(editForm,'endTime',$event)"/>
								</el-form-item>  
							</el-col>
							
						</el-row>
						<el-row>
							<el-col :span="8">
								<el-form-item label="完成时间" prop="finishTime">
									<el-date-picker type="date" placeholder="选择日期" :disabled="true" v-model="editForm.finishTime"  value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD"/>
								</el-form-item> 

							</el-col>
							<el-col :span="8">
								<el-form-item label="关闭时间" prop="closeTime">
									<el-date-picker type="date" placeholder="选择日期" :disabled="true" v-model="editForm.closeTime"  value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD"/>
								</el-form-item> 

							</el-col> 

							<el-col :span="8">
								<el-form-item label="结算时间" prop="setTime">
									<el-date-picker type="date" placeholder="选择日期" :disabled="true" v-model="editForm.setTime"  value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD"/>
								</el-form-item>

							</el-col>  
						</el-row> 
							<el-form-item label="备注" prop="remark">
								<el-input type="textarea" :rows="2" v-model="editForm.remark" placeholder="备注" :maxlength="255" @change="editSomeFields(editForm,'remark',$event)"/>
							</el-form-item>   
					</el-tab-pane>
					<el-tab-pane label="客户信息" name="2" > 
						<el-form-item label="下单机构号码" prop="obranchId">
							<el-input v-model="editForm.obranchId" :disabled="true" placeholder="下单机构号码" :maxlength="50"/>
						</el-form-item> 
						<el-form-item label="下单用户编号" prop="ouserid">
							<el-input v-model="editForm.ouserid" :disabled="true" placeholder="下单用户编号" :maxlength="50"/>
						</el-form-item> 
						<el-form-item label="下单用户名称" prop="ousername"  >
							<el-input v-model="editForm.ousername" placeholder="下单用户名称" :maxlength="255" @change="editSomeFields(editForm,'ousername',$event)"/>
						</el-form-item> 
						<el-form-item label="客户联系电话" prop="custPhone">
							<el-input v-model="editForm.custPhone" placeholder="客户联系电话" :maxlength="50" @change="editSomeFields(editForm,'custPhone',$event)"/>
						</el-form-item> 
						<el-form-item label="客户联系地址" prop="custAddress"  >
							<el-input v-model="editForm.custAddress" placeholder="客户联系地址" :maxlength="255" @change="editSomeFields(editForm,'custAddress',$event)"/>
						</el-form-item> 
						<el-form-item label="下单机构名称" prop="obranchName">
							<el-input v-model="editForm.obranchName" placeholder="下单机构名称" :maxlength="255"/>
						</el-form-item> 
						
						<el-form-item label="第三方账号编号" prop="topenId">
							<el-input v-model="editForm.topenId" :disabled="true" placeholder="第三方账号编号" :maxlength="50"/>
						</el-form-item> 
					</el-tab-pane>
					<el-tab-pane label="销售经理" name="31" >  
						<el-form-item label="销售经理编号" prop="saleUserid"  >
							<el-input v-model="editForm.saleUserid" placeholder="销售经理编号" :maxlength="50" @change="editSomeFields(editForm,'saleUserid',$event)"/>
						</el-form-item> 
						<el-form-item label="销售经理名称" prop="saleUsername"  >
							<el-input v-model="editForm.saleUsername" placeholder="销售经理名称" :maxlength="255" @change="editSomeFields(editForm,'saleUsername',$event)"/>
						</el-form-item> 
					</el-tab-pane>
					<el-tab-pane label="付款信息" name="3" >   
						<el-row :gutter="5">
							<el-col :span="12"> 
								<el-form-item label="支付方式" prop="payType">  
									<mdp-select item-code="tpAppPayType" :disabled="true" v-model="editForm.payType"/> 
								</el-form-item>   
								<el-form-item label="应付金额" prop="ofinalFee" >
									<el-input :disabled="true" v-model="editForm.ofinalFee" placeholder="最终订单价格、最终付款金额" :maxlength="10"/>
								</el-form-item> 
								<div v-if="editForm.status>2">
								<el-form-item label="付款时间" prop="payTime" >
									<el-date-picker :disabled="true" type="date" placeholder="选择日期" v-model="editForm.payTime"  value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD"/>
								</el-form-item> 
								<el-form-item label="付款确认时间" prop="payCtime" >
									<el-date-picker :disabled="true" type="date" placeholder="选择日期" v-model="editForm.payCtime"  value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD"/>
								</el-form-item> 
								<el-form-item label="付款订单号" prop="prepayId">
									<el-input :disabled="true" v-model="editForm.prepayId" placeholder="付款订单号（第三方返回）" :maxlength="50"  @change="editSomeFields(editForm,'prepayId',$event)"/>
								</el-form-item>   
								<el-form-item label="实际付款金额" prop="payAt" >
									<el-input :disabled="true" v-model="editForm.payAt" placeholder="最终付款金额-客户付款后回填" :maxlength="20" @change="editSomeFields(editForm,'payAt',$event)"/>
								</el-form-item> 
								</div>
							</el-col>
							<el-col v-if="editForm.payType=='1'" :span="12">
								<el-button v-if="!codeUrl" @click="createOrder">创建微信收款码</el-button>
								<qriously v-else :modelValue="codeUrl" :size="300" />
							</el-col> 
							<el-col v-else-if="editForm.payType=='2'" :span="12">
								<el-button @click="createOrder">创建支付宝收款码</el-button> 
							</el-col> 
						</el-row>
					</el-tab-pane>
					<el-tab-pane label="收款信息" name="32" >    
						<el-form-item label="收款银行编号 " prop="pbankId"  >
							<el-input v-model="editForm.pbankId" placeholder="收款银行编号(支付方式为3时必填)" :maxlength="50" @change="editSomeFields(editForm,'pbankId',$event)"/>
						</el-form-item> 
						<el-form-item label="收款银行名称 " prop="pbankName">
							<el-input v-model="editForm.pbankName" placeholder="收款银行名称(支付方式为3时必填)" :maxlength="255"  @change="editSomeFields(editForm,'pbankName',$event)"/>
						</el-form-item> 
						<el-form-item label="收款银行卡号 " prop="pbankCardNo">
							<el-input v-model="editForm.pbankCardNo" placeholder="收款银行卡号(支付方式为3时必填)" :maxlength="50"  @change="editSomeFields(editForm,'pbankCardNo',$event)"/>
						</el-form-item> 
						<el-form-item label="收款账户姓名 " prop="pbankUsername">
							<el-input v-model="editForm.pbankUsername" placeholder="收款账户姓名(支付方式为3时必填)" :maxlength="255"  @change="editSomeFields(editForm,'pbankUsername',$event)"/>
						</el-form-item> 
					</el-tab-pane>
					<el-tab-pane label="折扣信息" name="4" > 
						
						<el-form-item label="最新折扣率" prop="odisRate">
							<el-input  :disabled="!userInfo.isSuperAdmin && !userInfo.isPlatformAdmin" type="number" :max="100" :min="0"  v-model="odisRate" title="折扣率0.01-100之间，9.9折填99，9折填90,最小填0.01折">
								<template #append>
									<el-button @click="odisRateConfirm" :disabled="!userInfo.isSuperAdmin && !userInfo.isPlatformAdmin"> % &nbsp;确认修改折扣率</el-button>
								</template>
							</el-input>
						</el-form-item>  
					</el-tab-pane>
					<el-tab-pane label="产品列表" name="5" >
						<mo-order-module-index :mo-order="editForm" subOpType="list" :someOpen="false"/>
					</el-tab-pane>
					
					<el-tab-pane label="0元购审核" name="6" v-if="userInfo.isSuperAdmin">
  
						 <el-popconfirm
						 		width="400px"
								confirm-button-text="同意"
								cancel-button-text="不同意"
								:icon="InfoFilled"
								icon-color="#626AEF"
								title="该订单一旦进行0元购审核将视为已同意客户以0元实现已付款状态。客户不再需要支付订单金额，请谨慎使用。确认提交?"
								@confirm="orderPayZeroSubmit" 
							>
								<template #reference>
									<el-button type="warning">0元购审核提交</el-button>
								</template>
							</el-popconfirm>
					</el-tab-pane>
				</el-tabs>
        </el-form> 
		<el-row v-if="showBtn!==false"  class="footer">
				<el-button @click="close">关闭</el-button>
				<el-button v-if="currOpType=='add'" v-loading="load.edit" type="primary" @click="saveSubmit" :disabled="disBtn('addBtn') || !checkBtnQx('addBtn',menuDefId) || load.edit">提交</el-button>
		</el-row>  
</template>

<script>
import util from '@/components/mdp-ui/js/util';//全局公共库
import config from "@/api/mdp_pub/mdp_config"; //全局公共库import
import * as MoOrderApi from '@/api/mdp/mo/moOrder';
import { mapState } from 'pinia'
import { useUserStore } from '@/store/modules/user'
import { MdpFormMixin } from '@/components/mdp-ui/mixin/MdpFormMixin.js';

import {createOrder} from '@/api/mdp/sys/order'
import {aliPay, weixinPay, checkWxPayStatus} from '@/api/mdp/pay/pay'

import MoOrderModuleIndex from '../moOrderModule/Index.vue';
export default {
    name:'moOrderForm',
    mixins:[MdpFormMixin],
    components: {
        MoOrderModuleIndex
    },
    computed: {
			...mapState(useUserStore,['userInfo'])
    },
    props:{
    },
    watch: {
    },
    data() {
        return { 
            menuDefId:'',//menu_def.id 菜单表菜单编号，用于按钮权限判断
            pkNames:["id"],//表格主键的java属性名称，驼峰命名，默认为id,支持多主键
            
            editFormRules: {
                id:[
                //{ required: true, message: '此项必填', trigger: 'change' },
                //{ min: 1,max: 200, message: '长度在1到200之间', trigger: 'change'}
                ]
            },
            editForm: {
                id:'',name:'',obranchId:'',ouserid:'',ousername:'',moFinalFee:'',status:'',sstatus:'',ctime:'',payTime:'',payCtime:'',moOrginFee:'',ousers:'',ocates:'',omodules:'',poid:'',startTime:'',endTime:'',payType:'',payId:'',prepayId:'',topenId:'',pbankId:'',pbankName:'',pbankCardNo:'',pbankUsername:'',remark:'',finishTime:'',closeTime:'',setTime:'',odays:'',ofinalFee:'',odisRate:'',othFee:'',otype:'',osource:'',memType:'',atype:'',saleUserid:'',saleUsername:'',custPhone:'',custAddress:'',payAt:'',obranchName:'',ooper:'',tranId:'',invoice:'',invoiceTime:'',invoiceId:''
            },
			odisRate:null,
			codeUrl:null,
			timer:0,
            //增删改查(含批量)接口
            apis:{
                queryById: MoOrderApi.queryMoOrderById,
                add: MoOrderApi.addMoOrder,
                edit: MoOrderApi.editMoOrder,
                editSomeFields: MoOrderApi.editSomeFieldsMoOrder
            }
        }
    },
    methods: {
         //由组件扩展添加其它的初始页面的逻辑(mounted+onOpen都会调用此函数，建议只添加公共逻辑)
         initCurrData(){

         },
        /**
         * 检查参数是否满足调用后台接口的条件
         * @returns true / false
         */
        preParamCheck(params){

            return true;
        },


        /**
         * 对修改的字段进行判断，返回false ,将取消更新数据库,由组件扩展
         * @param {*} row 当前选中的行
         * @param {*} fieldName 修改的字段名
         * @param {*} $event 修改后的值
         * @param {*} params 将要提交服务器的参数
         * @returns true/false 返回false ,将取消更新数据库
         */
        editSomeFieldsCheck(row,fieldName,$event,params){
            params[fieldName]=$event
            return true;
        },
		odisRateConfirm(){
			if(this.odisRate>100){
						this.$message.error("折扣率不允许大于100")
						return false;
					}
			var params={$pks:[this.editForm.id],odisRate:this.odisRate}
			this.apis.editSomeFields(params).then(res=>{
				var tips = res.tips
				if(tips.isOk){
					Object.assign(this.editForm,res.data)
				}
				this.$message({ message: tips.msg, type: tips.isOk?'success':'error' });
			})
		},
		
		createOrder() {  
			let orderId = this.editForm.id;
			if(this.editForm.payType == '2') {
				this.toAliPay(orderId);
				return;
			}else if(this.editForm.payType == '1') {
				this.toWeixinPay(orderId);
				return;
			}else{
				this.$message({ message: "请选则支付方式", type:'error' });
				return;
			}
		},

		toAliPay(orderId) {
		let params = {
			id: orderId,
			otype: 1,
			returnUrl: `${window.location.protocol+"//"+window.location.host}/${import.meta.env.VITE_CONTEXT}/${import.meta.env.VITE_API_VERSION}/#/my/order/paySuccess`
		}
		aliPay(params).then(res => {
			if(res.tips.isOk) {
				let routerData = this.$router.resolve({path:'/my/order/alipay',query: {htmlStr: res.data.htmlStr}})
				// 打开新页面
				window.open(routerData.href, '_blank') 
			}else {
			this.$message.error(res.tips.msg);
			}
		}).finally(() => {
			setTimeout(() => {
			this.load.add = false;
			}, 2000);
		})
		},

		toWeixinPay(orderId) {
		let params = {
			id: orderId,
			otype: 1,
			returnUrl: ""
		}
		weixinPay(params).then(res => {
			if(res.tips.isOk) {
			this.codeUrl = res.data.codeUrl; 
			this.timer = setInterval(() => {
				this.queryOrderStatus(orderId,res.data.payId)
			}, 3000)
			}else {
			this.$message.error(res.tips.msg);
			}
		}).finally(() => {
			setTimeout(() => {
			this.load.add = false;
			}, 2000);
		})
		},
		orderPayZeroSubmit(){
			MoOrderApi.orderPayZero(this.editForm).then(res=>{
				let {tips}=res
				this.$message({message:tips.msg,type:tips.isOk?'success':'error'})
			})
		},
		//查询订单支付状态
		queryOrderStatus(orderId,payId) {
		console.log("查询订单");
		checkWxPayStatus({'orderId': orderId, "otype": "1","payId":payId}).then(res => {
			if(res.tips.isOk) {
			this.$router.push({path:'/my/order/paySuccess', query:{total_amount: this.editForm.ofinalFee, out_trade_no: orderId,pay_id:payId}});
			clearInterval(this.timer);
			}else {
			}
		}).finally(() => {

		})
		},
    },
    mounted() {

    }
}

</script>

<style scoped>

</style>